import { Tag } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { getUserById } from '../api/user';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import PropTypes from 'prop-types';

function IssueItem(props) {
  const colorArr = ['#108ee9', '#2db7f5', '#f50', 'green', '#87d068', 'blue', 'red', 'purple'];
  const [userInfo, setUserInfo] = useState(null);
  const { typeList } = useSelector((state) => state.type);
  const navigate = useNavigate();

  useEffect(() => {
    async function getUserInfo() {
      const response = await getUserById(props.issueInfo?.userId);
      setUserInfo(response.data);
    }

    getUserInfo();
  }, []);

  const date = dayjs(props.issueInfo.issueDate).format('YYYY-MM-DD HH:mm:ss');
  const type = typeList.find((item) => item._id === props.issueInfo.typeId);
  const typeColor = colorArr[typeList.indexOf(type) % colorArr.length];

  const gotoIssueDetail = () => {
    navigate(`/issues/${props.issueInfo._id}`);
  };
  return (
    <div className="flex">
      {/* 回答数 */}
      <div className="w-20 text-center text-md text-gray-500">
        <div className="">{props.issueInfo.commentNumber}</div>
        <div>回答</div>
      </div>
      {/* 浏览数 */}
      <div className="w-20 text-center text-md text-gray-500">
        <div className="">{props.issueInfo.scanNumber}</div>
        <div>浏览</div>
      </div>
      {/* 问题内容 */}
      <div className="grow relative flex flex-col justify-between">
        <h3 className="text-lg cursor-pointer" onClick={gotoIssueDetail}>
          {props.issueInfo.issueTitle}
        </h3>
        <div className="flex justify-between mt-2">
          <div className="">
            <Tag color={typeColor}>{type?.typeName}</Tag>
          </div>
          <div className="time">
            <Tag color="pink">{userInfo?.nickname}</Tag>
            <span>{date}</span>
          </div>
        </div>
      </div>
    </div>
  );
}
IssueItem.propTypes = {
  issueInfo: PropTypes.shape({
    _id: PropTypes.string.isRequired,
    userId: PropTypes.string.isRequired,
    typeId: PropTypes.string.isRequired,
    issueDate: PropTypes.string.isRequired,
    issueTitle: PropTypes.string.isRequired,
    commentNumber: PropTypes.number.isRequired,
    scanNumber: PropTypes.number.isRequired,
  }).isRequired,
};

export default IssueItem;
